package com.example.webapp.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Map;

@Slf4j
@Service
public class HttpDebugService {
    
    @Autowired
    private RestTemplate restTemplate;

    public ResponseEntity<String> sendRequest(String url, String method, 
            Map<String, String> headers, Map<String, String> params, String body) {
        try {
            // 构建URL（添加查询参数）
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
            if (params != null) {
                params.forEach(builder::queryParam);
            }
            String finalUrl = builder.build().encode().toUriString();

            // 构建请求头
            HttpHeaders httpHeaders = new HttpHeaders();
            if (headers != null) {
                headers.forEach(httpHeaders::add);
            }

            // 构建请求体
            HttpEntity<String> requestEntity = new HttpEntity<>(body, httpHeaders);

            // 发送请求
            return restTemplate.exchange(
                finalUrl,
                HttpMethod.valueOf(method.toUpperCase()),
                requestEntity,
                String.class
            );
        } catch (Exception e) {
            log.error("Error sending request: ", e);
            throw e;
        }
    }
} 